﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.MobileControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Xml;
using OTS.Model;
using OTS.BLL;

public partial class product : System.Web.UI.Page
{
    protected string strBigPic;
    protected string strColor;
    protected string strSize;
    protected string strConsulting;
    protected string strEvaluation;
    custom cus = new custom();
    List<Consulting> conList = new List<Consulting>();
    ProductBLL productBll = new ProductBLL();
    ConsultingBLL conBLL = new ConsultingBLL();
    ProductTypeBLL protypeBLL = new ProductTypeBLL();
    ProductSizeBLL prosizeBLL = new ProductSizeBLL();
    DataTable dt = new DataTable();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string proID = Request.QueryString["proID"];
            Product product = new Product();
            product = productBll.GetSingleProduct(Convert.ToInt32(proID));
            if (product == null)
            {
                Response.Redirect("Index.aspx");
                return;
            }
            if (product.bigImg_pic == "")
            {
                //this.imgBigImg.ImageUrl = "img/yes_picture.gif";
                BigPic("img/yes_picture.gif");
            }
            else
            {
                //this.imgBigImg.ImageUrl = product.bigImg_pic;//"img/T1bf6LXe4XXXXqr23T_011632.jpg_460x460[1].jpg";
                //this.Image3.ImageUrl = product.bigImg_pic;//"img/T1bf6LXe4XXXXqr23T_011632.jpg_460x460[1].jpg";
                BigPic(product.bigImg_pic);
            }
            if (product.basicInformation_pic == "")
            {
                this.imgBasicInformation_pic.ImageUrl = "img/yes_picture.gif";
            }
            else
            {
                this.imgBasicInformation_pic.ImageUrl = product.basicInformation_pic;
            }
            if (product.Brand.brand_rightpiclogo == "")
            {
                this.imgBandPic.ImageUrl = "img/yes_picture.gif";
            }
            else
            {
                this.imgBandPic.ImageUrl = product.Brand.brand_rightpiclogo;
            }

            this.lblTitle.Text = product.title + " " + product.proNO;
            this.txtTitle.Value = "[咨询]" + product.title;
            this.lblWholeSalePrice.Text = Convert.ToString(product.wholeSalePrice);
            if (product.retailPrice == 0 || product.retailPrice == product.wholeSalePrice)
            {
                this.lblRetailPrice.Text = Convert.ToString(product.wholeSalePrice);
                this.lblDiscount.Text = "0";
                this.lblSave.Text = "0";
            }
            else
            {
                this.lblRetailPrice.Text = Convert.ToString(product.retailPrice);
                double discount = (product.retailPrice / product.wholeSalePrice) * 10;
                this.lblDiscount.Text = discount.ToString("f1");
                double save = product.wholeSalePrice - product.retailPrice;
                this.lblSave.Text = Convert.ToString(save);
            }
            this.lblProNO.Text = product.proNO;
            this.lblProNO2.Text = product.proNO;
            this.lblProName.Text = product.Brand.brand_name;
            this.lblProName2.Text = product.proName;
            switch (product.expirySeason)
            {
                case 1:
                    this.lblExpirySeason.Text = "夏季";
                    break;
                case 2:
                    this.lblExpirySeason.Text = "秋季";
                    break;
                case 3:
                    this.lblExpirySeason.Text = "冬季";
                    break;
                default:
                    this.lblExpirySeason.Text = "春季";
                    break;
            }
            this.lblEspecial.Text = product.especial;
            this.lblWholeSalePrice2.Text = product.wholeSalePrice.ToString();
            this.lblMaterial.Text = product.material;
            this.lblDes.Text = product.des;
            //截取数据库取出的图片信息
            //创建表
            DataSet ds = new DataSet("ShowPic");   //创建一个名为ShowPic的DataSet
            DataTable dt = new DataTable("ShowPic");    //创建名为ShowPic的DataTable
            dt.Columns.Add(new DataColumn("sp_id", typeof(int)));
            dt.Columns.Add(new DataColumn("sp_showpic", typeof(string)));

            //截取展示图片
            string strShow = product.show_pic;
            string[] strShowImg = strShow.Split(',');

            for (int i = 0; i < strShowImg.Length; i++)
            {
                DataRow dr = dt.NewRow();
                dr["sp_id"] = i + 1;
                if (strShowImg[i] == "")
                {
                    dr["sp_showpic"] = "img/yes_picture.gif";
                }
                else
                {
                    dr["sp_showpic"] = strShowImg[i];
                }
                dt.Rows.Add(dr);
            }
            ds.Tables.Add(dt);
            this.rtShowPic.DataSource = ds;
            this.rtShowPic.DataBind();

            DataSet dSet = new DataSet("DetailsPic");   //创建一个名为DetailsPic的DataSet
            DataTable dTable = new DataTable("DetailsPic");    //创建名为DetailsPic的DataTable
            dTable.Columns.Add(new DataColumn("dp_id", typeof(int)));
            dTable.Columns.Add(new DataColumn("dp_detailspic", typeof(string)));

            //截取细节图
            string strDetails = product.details_pic;
            string[] strDetailsImg = strDetails.Split(',');
            for (int j = 0; j < strDetailsImg.Length; j++)
            {
                DataRow dRow = dTable.NewRow();
                dRow["dp_id"] = j + 1;
                if (strDetailsImg[j] == "")
                {
                    dRow["dp_detailspic"] = "img/yes_picture.gif";
                }
                else
                {
                    dRow["dp_detailspic"] = strDetailsImg[j];
                }
                dTable.Rows.Add(dRow);
            }
            dSet.Tables.Add(dTable);
            this.rpDetailsPic.DataSource = dSet;
            this.rpDetailsPic.DataBind();

            BindColor(product.color);
            BindSize(product.sizeIDs);
            SalesRecord(Int32.Parse(proID));
            Cookies(proID);
            BindShowSize(proID);
            BindEvaluation(Int32.Parse(proID));
            BindConsulting(Int32.Parse(proID));
        }
    }

    /// <summary>
    /// 填充放大镜图片方法
    /// </summary>
    private void BigPic(string pic) {
        StringBuilder sb = new StringBuilder();
        string strUrl = pic.Replace("\\", "/");
        string strImgUrl = strUrl.Replace("~/", "");

        sb.Append("<img src=\"" + strImgUrl + "\" width=\"350\" height=\"350\"  jqimg=\"" + strImgUrl + "\"/>");
        strBigPic = sb.ToString();
    }

    /// <summary>
    /// 获得商品颜色
    /// </summary>
    /// <param name="colorID"></param>
    private void BindColor(string colorID)
    {
        if (colorID.Trim() == "")
        {
            return;
        }
        color col = new color();
        ColorBLL colorBLL = new ColorBLL();
        DataTable dt = new DataTable();
                
        string[] strCol = colorID.Split(',');
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < strCol.Length; i++)
        {
            col = colorBLL.GetColorByID(strCol[i]);
            
            sb.Append("<li value=\"" + col.colID + "\">");
            sb.AppendFormat("<a href=\"#\"><span>" + col.col_color + "</span><i></i></a>");
            sb.Append("</li>");
        }
        strColor = sb.ToString();
    }

    /// <summary>
    /// 获得商品尺码
    /// </summary>
    /// <param name="colorID"></param>
    private void BindSize(string sizeID)
    {
        if (sizeID.Trim() == "")
            return;
        DataTable dt = new DataTable();
        string[] size = sizeID.Split(',');
        StringBuilder sb=new StringBuilder();

        for (int i = 0; i < size.Length; i++)
        {
            dt = prosizeBLL.GetBySizeID(Convert.ToInt32(size[i]));
            sb.Append("<li value=\"" + dt.Rows[0]["sizeID"].ToString() + "\">");
            sb.AppendFormat("<a href=\"#\"><span>" + dt.Rows[0]["sizeName"].ToString() + "</span><i></i></a>");
            sb.Append("</li>");
        }
        strSize = sb.ToString();
    }

    string[] strPro;
    int count = 0;  //记录strPro数据中有没有包含重复的ID
    private void Cookies(string proID)
    {
        if (Request.Cookies["pro"] != null) //如果cookies存在的话，就在原先cookies上修改
        {
            string pro = Request.Cookies["pro"]["proID"].ToString();
            string times = Request.Cookies["pro"]["times"].ToString();

            if (pro.Split(',').Length > 0)
            {
                strPro = pro.Split(',');
            }
            //循环strPro数组，判断数组中有没有包含重复的ID，有的话count+1
            for (int i = 0; i < strPro.Length; i++)
            {
                if (strPro[i] == proID)
                {
                    count += 1;
                }
            }
            //count==0代表数组中没有重复的数据，反之
            if (count == 0)
            {
                pro = pro + "," + proID;
                times = times + "," + System.DateTime.Now.ToString();

                //修改cookies
                Response.Cookies["pro"]["proID"] = pro;
                Response.Cookies["pro"]["times"] = times;
            }
        }
        else  //不存在cookies的话，创建一个新的cookies
        {
            HttpCookie cookie = new HttpCookie("pro");    //定义cookie对象
            DateTime dt = DateTime.Now; //定义时间对象
            TimeSpan ts = new TimeSpan(10, 10, 1000, 1000000);  //cookie有效作用时间
            cookie.Expires = dt.Add(ts);    //添加作用时间
            //增加属性
            cookie.Values.Add("proID", proID);
            cookie.Values.Add("times", System.DateTime.Now.ToString());
            Response.AppendCookie(cookie);  //确定写入cookie中
        }
    }

    private void SalesRecord(int proID)
    {
        SalesRecordBLL srBLL = new SalesRecordBLL();
        DataTable dt = new DataTable();

        dt = srBLL.GetBySalesRecord(proID);
        if (dt.Rows.Count > 0)
        {
            //截取数据库取出的图片信息
            //创建表
            DataSet ds = new DataSet("SalesRecord");   //创建一个名为ShowPic的DataSet
            DataTable table = new DataTable("SalesRecord");    //创建名为ShowPic的DataTable
            table.Columns.Add(new DataColumn("salR_id", typeof(int)));
            table.Columns.Add(new DataColumn("salR_userName", typeof(string)));
            table.Columns.Add(new DataColumn("salR_number", typeof(int)));
            table.Columns.Add(new DataColumn("salR_wholeSalePrice", typeof(float)));
            table.Columns.Add(new DataColumn("salR_retailPrice", typeof(float)));
            table.Columns.Add(new DataColumn("salR_date", typeof(DateTime)));

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = table.NewRow();
                dr["salR_id"] = i + 1;
                dr["salR_userName"] = dt.Rows[i]["cusName"].ToString();
                dr["salR_number"] = dt.Rows[i]["pcount"];

                if (Convert.ToInt32(dt.Rows[i]["retailPrice"].ToString()) == 0)
                {
                    dr["salR_wholeSalePrice"] = dt.Rows[i]["wholeSalePrice"].ToString();
                }
                else
                {
                    dr["salR_wholeSalePrice"] = dt.Rows[i]["retailPrice"].ToString();
                }
                dr["salR_date"] = dt.Rows[i]["sr_dateTime"].ToString();
                table.Rows.Add(dr);
            }
            ds.Tables.Add(table);


            this.rpSalesRecord.DataSource = ds;
            this.rpSalesRecord.DataBind();
            this.rpSalesRecord.Visible = true;
        }
        else
        {
            this.lblMsg.Text = "暂时还没有买家购买此商品。";
            this.lblMsg.CssClass = "divDisplayB";
            this.rpSalesRecord.Visible = false;
        }

        dt = srBLL.GetTotalSalesRecord(proID);
        this.lblNumber.Text = dt.Rows[0]["total"].ToString();
        this.lblNum.Text = dt.Rows[0]["total"].ToString();
    }

    /// <summary>
    /// 获得商品尺码
    /// </summary>
    /// <param name="colorID"></param>
    protected void BindShowSize(string proID)
    {
        DataTable dt = new DataTable();
        DataTable dTable = new DataTable();
        dt = productBll.GetAllProduct("where proID=" + proID);
        string[] strColorID = (dt.Rows[0]["sizeIDs"].ToString()).Split(',');
        string sId = "";

        for (int i = 0; i < strColorID.Length; i++)
        {
            sId = strColorID[i];
            if (sId != "")
            {
                if (OTS.Common.Help.IsNumber(sId))
                {
                    break;
                }
            }
        }
        if (sId == "")
        {
            return;
        }
        string strMatId = prosizeBLL.GetMatIdBySizeId(sId);
        size_Table sTable = prosizeBLL.CreateSizeTable(Int32.Parse(strMatId));
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.Append("<table width='700' border='0' cellpadding='0' cellspacing='0' bgcolor='#cccccc' style='text-align: center; margin: 5px 0px; font-size: 12px'>");
        sb.Append("<tbody>");
        sb.Append("<tr height='32' style='color: #fff; line-height: 180%;'>");
        sb.Append("<td style='width: 127px'>名称</td>");
        for (int i = 0; i < sTable.Header.Count; i++)
        {
            sb.AppendFormat("<td>{0}</td>", sTable.Header[i].ToString());
        }
        sb.Append("</tr>");
        for (int j = 0; j < sTable.Columns.Count; j++)
        {
            int numJ = j + 1;
            sb.Append("<tr>");
            if (numJ % 2 == 0)
            {
                sb.AppendFormat("<td bgcolor='#f7f7f7' style='border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid;border-top: medium none; border-right: #cccccc 1px solid; line-height: 180%;width: 127px;'>{0}</td>", sTable.Columns[j].ColumnName);
                for (int k = 0; k < sTable.Columns[j].listValue.Count; k++)
                {
                    sb.AppendFormat("<td bgcolor='#f7f7f7' style='border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid;border-top: medium none; border-right: #cccccc 1px solid; line-height: 180%;width: 127px;'>{0}</td>", sTable.Columns[j].listValue[k].ToString());
                }
            }
            else
            {
                sb.AppendFormat("<td bgcolor='#ffffff' style='border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid;border-top: medium none; border-right: #cccccc 1px solid'>{0}</td>", sTable.Columns[j].ColumnName);
                for (int a = 0; a < sTable.Columns[j].listValue.Count; a++)
                {
                    sb.AppendFormat("<td bgcolor='#ffffff' style='border-bottom: #cccccc 1px solid; border-left: #cccccc 1px solid;border-top: medium none; border-right: #cccccc 1px solid'>{0}</td>", sTable.Columns[j].listValue[a].ToString());
                }
            }


            sb.Append("</tr>");
        }
        sb.Append("</tbody>");
        sb.Append("</table>");
        this.sizeTable.InnerHtml = sb.ToString();
    }
    //收藏
    protected void lbtnFav_Click(object sender, EventArgs e)
    {
        Favorite favorite = new Favorite();
        FavoriteBLL favoriteBLL = new FavoriteBLL();
        if (Session["custom"] != null)
        {
            cus = (custom)Session["custom"];
            string proID = Request.QueryString["proID"];
            favorite.cusID = cus.cusID;
            favorite.proID = Int32.Parse(proID);
            DataTable dt = favoriteBLL.GetByFav("where cusID=" + cus.cusID + " and proID=" + Int32.Parse(proID));
            if (dt.Rows.Count > 0)
            {
                JavascriptAlert("您已经收藏过此宝贝了！");
                this.panelShowCart.CssClass = "divDisplayN";
                this.upFav.Update();
                return;
            }
            else
            {
                if (favoriteBLL.Add(favorite))
                {
                    JavascriptAlert("恭喜您，宝贝收藏成功！");
                    this.panelShowCart.CssClass = "divDisplayN";
                }
                else
                {
                    JavascriptAlert("很抱歉，收藏失败！");
                    this.panelShowCart.CssClass = "divDisplayN";
                }
                this.upFav.Update();
            }
        }
        else
        {
            Response.Redirect("login.aspx?redirectUrl=" + Request.RawUrl.ToString());
        }
    }

    private void JavascriptAlert(string message)
    {
        ScriptManager.RegisterClientScriptBlock(this.UpdatePanelAlert, typeof(UpdatePanel), "alert1", "alert('" + message + "')", true);
        this.UpdatePanelAlert.Update();
    }
    protected void btnCart_Click(object sender, EventArgs e)
    {
        Cart cart = new Cart();
        CartBLL cartBll = new CartBLL();

        if (Session["custom"] != null)
        {
            string proID = Request.QueryString["proID"];
            cus = (custom)Session["custom"];
            cart.cusID = cus.cusID;
            cart.proID = Int32.Parse(proID);
            if (this.txtCount.Value != "0" && this.txtColor.Text != "" && this.txtSize.Text != "")
            {
                cart.count = Convert.ToInt32(this.txtCount.Value);
                cart.colID = Convert.ToInt32(this.txtColor.Text);
                cart.sizeID = Convert.ToInt32(this.txtSize.Text);
                DataTable dt = cartBll.GetByCart("where cusID=" + cus.cusID + " and proID=" + Int32.Parse(proID));
                if (dt.Rows.Count > 0)
                {
                    JavascriptAlert("此商品已在您的购物车中！");
                    this.panelShowCart.CssClass = "divDisplayN";
                    this.upFav.Update();
                    return;
                }
                else
                {
                    if (cartBll.AddCart(cart))
                    {
                        dt = cartBll.GetByCart("where cusID=" + cus.cusID);

                        DataTable dTable = new DataTable();
                        dTable = cartBll.GetCartProTotle(cus.cusID);
                        this.lblTotle.Text = dTable.Rows[0]["totle"].ToString();
                        this.lblPriceTotle.Text = dTable.Rows[0]["totalCount"].ToString();
                        this.lblCout.Text = dTable.Rows[0]["coutTotle"].ToString();
                        this.panelShowCart.CssClass = "divDisplayB";
                        this.upFav.Update();
                    }
                    else
                    {
                        JavascriptAlert("对不起，添加到购物车失败！");
                        this.upFav.Update();
                    }
                }
            }
            else
            {
                JavascriptAlert("您还没有进行相关选择！");
                return;
            }
        }
        else
        {
            Response.Redirect("login.aspx?redirectUrl=" + Request.RawUrl.ToString());
        }
    }

    //加载评价
    protected void BindEvaluation(int proID)
    {
        CustomBLL cusBLL = new CustomBLL();
        EvaluationBLL eBLL = new EvaluationBLL();
        DataTable dTable = eBLL.GetProETotal(proID);

        StringBuilder sb = new StringBuilder();

        if (dt.Rows.Count>0)
        {
            this.lblETotal.Text = dTable.Rows[0]["total"].ToString();
        }
        else
        {
            this.lblETotal.Text = "0";
        }
        dt = eBLL.GetProE(proID);
        if (dt.Rows.Count>0)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                sb.Append("<div class=\"boxBrown division clearfix\" style=\"margin-bottom: 10px; display: block;padding: 7px;\">");
                sb.Append("<div class=\"floatLeft commentMain\">");
                cus = cusBLL.GetModel(Convert.ToInt32(dt.Rows[i]["cusID"].ToString()));
                sb.AppendFormat("<span class=\"fontcolorOrange\">" + cus.cusLoginName + "</span>说：");
                sb.AppendFormat("<span class=\"timpstamp font10px fontcolorGray\">" + dt.Rows[i]["addTime"].ToString() + "</span>");
                sb.Append("<div style=\"clear: both;\"></div>");
                sb.AppendFormat("<div class=\"commentText\">" + dt.Rows[i]["experience"].ToString() + "</div>");
                sb.Append("</div>");
                sb.Append("</div>");
            }
        }
        else
        {
            sb.Append("<span style=\"margin-left: 5px;\">很抱歉，暂无该商品的评价！</span>");
        }
        strEvaluation = sb.ToString();
    }

    //加载购买咨询
    protected void BindConsulting(int proID)
    {
        CustomBLL cusBLL = new CustomBLL();
        conList = conBLL.GetConsulting(proID);
        StringBuilder sb = new StringBuilder();

        if (conList!=null)
        {
            for (int i = 0; i < conList.Count; i++)
            {
                sb.Append("<div class=\"boxBrown division clearfix\" style=\"margin-bottom:0px;display:block;padding:7px;\">");
                sb.Append("<div class=\"floatLeft commentMain\">");
                if (Convert.ToInt32(conList[i].cusID) == 0)
                {
                    sb.Append("<span class=\"fontcolorOrange\">非会员顾客</span>说：");
                }
                else
                {
                    cus = cusBLL.GetModel(Convert.ToInt32(conList[i].cusID));
                    sb.AppendFormat("<span class=\"author fontcolorOrange\">" + cus.cusLoginName + "</span>说：");
                }
                sb.AppendFormat("<span class=\"font10px fontcolorGray\">" + conList[i].addTime + "</span>");
                sb.Append("<div style=\"clear:both;\"></div>");
                sb.AppendFormat("<div class=\"commentText\">" + conList[i].context + "</div>");
                sb.Append("</div>");
                sb.Append("</div>");
                sb.Append("<div class=\"commentReply\">");

                dt = conBLL.GetReply(conList[i].conID);
                if (dt.Rows.Count>0)
                {
                    for (int j = 0; j < dt.Rows.Count; j++)
                    {
                        sb.Append("<div class=\"division\" style=\" margin:0px;padding:7px;\">");
                        sb.Append("<div class=\"floatLeft commentReply-admin\">回答</div>");
                        sb.Append("<span class=\"fontcolorOrange\"><b>管理员</b></span> 回复：");
                        sb.AppendFormat("<span class=\"font10px fontcolorGray\">" + dt.Rows[j]["addTime"].ToString() + "</span>");
                        sb.Append("<div style=\"clear:both;\"></div>");
                        sb.AppendFormat("<div class=\"commentText\">" + dt.Rows[j]["context"].ToString() + "</div>");
                        sb.Append("</div>");
                    }
                }
                sb.Append("</div>");
            }
        }
        else
        {
            sb.Append("<span style=\"margin-left: 5px;\">如果您对本商品有什么问题,建议您联系网站的QQ或旺旺客服,可以及时得到回复，如客服人员离线可在这里提问！</span>");
        }
        strConsulting = sb.ToString();

        dt = conBLL.GetConsultingTotal(proID);
        if (dt.Rows.Count>0)
        {
            this.lblTotal.Text = dt.Rows[0]["total"].ToString();
        }
        else
        {
            this.lblTotal.Text = "0";
        }
    }
    protected void btnSubmin_Click(object sender, EventArgs e)
    {
        cus = (custom)Session["custom"];
        Consulting con = new Consulting();
        string strCookie = Request.Cookies.Get("CheckCode").Value;
        string strCode = this.validate.Value.ToUpper();

        if (Request.Form["comment"] == "")
        {
            JavascriptAlert("请输入您要咨询的内容");
            this.upConsulting.Update();
            return;
        }
        if (Request.Cookies["CheckCode"] == null)
        {
            JavascriptAlert("请输入验证码");
            this.upConsulting.Update();
            return;
        }
        if (strCode!=strCookie)
        {
            JavascriptAlert("验证码错误，请重新输入");
            this.upConsulting.Update();
            return;
        }
        if (cus!=null)
        {
            con.conID = cus.cusID;
        }
        else
        {
            con.conID = 0;
        }

        con.proID = Convert.ToInt32(Request.QueryString["proID"]);
        if (this.contact.Value!="")
        {
            con.contact = this.contact.Value;
        }
        string str = this.txtTitle.Value.Replace("[咨询]", "");
        con.title = str;
        con.context = Request.Form["comment"].ToString();
        if (conBLL.AddConsulting(con))
        {
            BindConsulting(Convert.ToInt32(Request.QueryString["proID"]));
            this.upConsulting.Update();
        }
        else
        {
            JavascriptAlert("提交咨询失败！");
            this.upConsulting.Update();
        }
    }
    protected void btnJieSuan_Click(object sender, EventArgs e)
    {
        cus = (custom)Session["custom"];
        if (cus==null)
        {
            Response.Redirect("login.aspx?redirectUrl=" + Request.RawUrl.ToString());
        }
        else
        {
            Response.Redirect("cart.aspx");
        }
    }
}
